<template>
    <div style="margin-left: 2%;margin-right: 2%;margin-top: 10px">
        <el-card>
            <span style="font-size: 13px">单位名称：</span>
            <el-input v-model="search.orgName" placeholder="请输入内容" style="width: 130px"></el-input>

            <span style="font-size: 13px;margin-left: 3%">登录名：</span>
            <el-input v-model="search.loginName" placeholder="请输入内容" style="width: 130px"></el-input>


            <span style="font-size: 13px;margin-left: 3%">用户名：</span>
            <el-input v-model="search.userName" placeholder="请输入内容" style="width: 130px"></el-input>

            <div style="display: inline;margin-left: 10%">
                <el-button size="mini" @click="searchCondition(1)" type="primary">查询</el-button>
                <el-button size="mini" @click="clearMes" type="primary">清空查询</el-button>

            </div>
        </el-card>
        <div style="margin-top: .8%;text-align: right;margin-right: 30px">
            <el-button size="mini" type="primary" @click="centerDialogVisible = true">添加用户</el-button>
        </div>
        <div style="margin-top: 7px;margin-bottom: 10px">


            <el-table
                    :data="userTable"
                    border
                    v-loading="loading"
                    style="width: 100%">
                <el-table-column
                        prop="orgName"
                        min-width="170px"
                        label="单位名称"
                >
                </el-table-column>
                <el-table-column
                        prop="loginName"
                        min-width="209px"
                        label="账号"
                >
                </el-table-column>
                <el-table-column
                        prop="usersName"
                        min-width="209px"
                        label="用户姓名"
                >
                </el-table-column>
                <el-table-column
                        prop="roleName"
                        min-width="130px"
                        label="角色名称">
                </el-table-column>
                <el-table-column
                        width="120px"
                        label="操作"
                >
                    <template slot-scope="{$index,row}">
                        <!--            <el-tooltip placement="top" style="margin-left: 30%">-->
                        <!--              <div slot="content">删除</div>-->
                        <i title="删除" @click="delUser(row)" style="color: #e54e4e;margin-right: 20px"
                           class="el-icon-delete-solid"></i>
                        <!--            </el-tooltip>-->
                        <!--            <el-tooltip placement="top" style="margin-left: 30%">-->
                        <!--              <div slot="content">重置密码</div>-->
                        <i title="重置密码" @click="confirmPassword(row)" style="color: #e54e4e"
                           class="el-icon-key"></i>
                        <!--            </el-tooltip>-->
                    </template>
                </el-table-column>
            </el-table>

        </div>
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[20, 50, 100, 200]"
                :page-size="theData.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>

        <!--    添加用户-->
        <el-dialog
                title="添加用户"
                :visible.sync="centerDialogVisible"
                width="39%"
                center>
            <el-form ref="addUser" :rules="rules" :model="addUser" label-width="80px">
                <el-form-item label="单位名称" prop="orgId">
                    <el-select v-model="addUser.orgId" placeholder="请选择单位名称">
                        <template slot="default" v-for="(item) in options">
                            <el-option :label="item.orgName" :value="item.orgId"></el-option>
                        </template>
                    </el-select>
                </el-form-item>
                <el-form-item label="角色名称" prop="roleId">
                    <el-select v-model="addUser.roleId" placeholder="请选择单位名称">
                        <el-option label="采购管理员" value="2"></el-option>
                        <el-option label="采购员" value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="账号" prop="loginName">
                    <el-input v-model="addUser.loginName" placeholder="请输入账号">
                    </el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addUser.password" placeholder="请输入密码" show-password>
                    </el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="repeatPassword">
                    <el-input v-model="addUser.repeatPassword" show-password placeholder="请确认密码"></el-input>
                </el-form-item>
                <el-form-item label="用户姓名" prop="usersName">
                    <el-input v-model="addUser.usersName" placeholder="请确认用户姓名"></el-input>
                </el-form-item>
            </el-form>
            <div style="text-align: center">
                <el-button @click="cancelAddUser">取 消</el-button>
                <el-button type="primary" @click="submitUser">提 交</el-button>
            </div>
        </el-dialog>

        <!--    重置密码-->
        <el-dialog
                title="重置密码"
                :visible.sync="showReset"
                width="40%"
                center>
            <el-form ref="form" :rules="rules" :model="resetPassword" label-width="120px">
                <el-form-item prop="password" label="新的密码">
                    <el-input v-model="resetPassword.password" show-password placeholder="请输入新的密码">
                    </el-input>
                </el-form-item>
                <el-form-item prop="repeatAPassword" label="确认密码">
                    <el-input v-model="resetPassword.repeatAPassword" placeholder="请再次输入新的密码" show-password>
                    </el-input>
                </el-form-item>
            </el-form>
            <div style="text-align: center">
                <el-button @click="cancelReset">取 消</el-button>
                <el-button type="primary" @click="submitReset">提 交</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {deleteUser, getAllOrg, getAllUser, reqConditionSer, reqResetPassword, sysAddUSer} from "@/api/sysUser";
import pagination from '@/components/pagination/index.vue'
import user from "@/store/modules/user";

export default {
    name: 'index',
    computed: {
        user() {
            return user
        }
    },
    data() {
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.addUser.password) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }
        var validatePass1 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.resetPassword.password) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }
        return {
            rules: {
                orgId: [{required: true, message: '请选择单位', trigger: ['blur', 'change']}],
                roleId: [{required: true, message: '请选择角色', trigger: ['blur', 'change']}],
                loginName: [{required: true, message: '请输入账号', pattern: '[^ \x22]+', trigger: 'blur'}, {
                    min: 1,
                    max: 255,
                    message: '长度在 1 到 255 个字符',
                    trigger: 'blur'
                }],
                usersName: [{required: true, message: '请输入用户名', pattern: '[^ \x22]+', trigger: 'blur'}, {
                    min: 1,
                    max: 255,
                    message: '长度在 1 到 255 个字符',
                    trigger: 'blur'
                }],
                password: [{required: true, message: '请输入密码', pattern: '[^ \x22]+', trigger: 'blur'}, {
                    min: 1,
                    max: 255,
                    message: '长度在 1 到 255 个字符',
                    trigger: 'blur'
                }],
                repeatPassword: [{required: true, validator: validatePass2, trigger: 'blur'}, {
                    min: 1,
                    max: 255,
                    message: '长度在 1 到 255 个字符',
                    trigger: 'blur'
                }],
                repeatAPassword: [{required: true, validator: validatePass1, trigger: 'blur'}, {
                    min: 1,
                    max: 255,
                    message: '长度在 1 到 255 个字符',
                    trigger: 'blur'
                }],
                nowPassword: [{
                    required: true,
                    message: '请输入当前密码',
                    pattern: '[^ \x22]+',
                    trigger: 'blur'
                }, {min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur'}],
            },
            // dynamicTags: ['标签一', '标签二', '标签三'],
            currentPage: 1,
            search: {
                orgName: '',
                userName: '',
                loginName: ''
            },
            resetPassword: {
                password: "",
                repeatAPassword: '',
            },
            userId: JSON.parse(localStorage.getItem("userinfo")).userId,
            showReset: false,
            addUser: {
                orgId: '',
                roleId: '',
                usersName: '',
                loginName: '',
                password: '',
                repeatAPassword: '',
            },
            theData: {
                page: 1,
                pageSize: 20,
            },
            options: [],
            value: '',
            centerDialogVisible: false,
            total: 0,
            loading: true,
            userTable: [],
            isLoginUser: true,
            loginName: "",
        }
    },
    mounted() {
        this.getAllUser()
        this.getAllUnit()
    },
    components: {
        pagination
    },
    methods: {
        // 获得单位名称
        async getAllUnit() {
            let res = await getAllOrg()
            if (res.data.code === 200) {

                this.options = res.data.data
                console.log(this.options)

            } else {
                this.$message.error(res.data.msg);
            }
        },
        // 条件获得用户表
        async searchCondition(data) {
            this.loading = true
            try {
                let theDatas = {
                    orgName: this.search.orgName,
                    loginName: this.search.loginName || '',
                    userName: this.search.userName,
                }
                if (data === 1) {
                    this.currentPage = 1
                }
                let pageInfo = this.currentPage + "/" + this.theData.pageSize
                let res = await reqConditionSer(pageInfo, theDatas)
                if (res) {
                    this.loading = false
                }
                if (res.data.code === 200) {
                    this.userTable = res.data.data.record
                    this.total = res.data.data.total
                } else {
                    this.userTable = [];
                    this.total = 0;
                    this.$message(res.data.msg);
                }
            } catch (e) {
                this.$message.error(e.messages)
            } finally {
                this.loading = false
            }
        },
        clearMes(){
            this.showPageSearch=false
            Object.keys(this.search).forEach(index=>this.search[index]='')
        },
        // 添加用户信息
        async submitUser() {
            this.$refs.addUser.validate(async (valid) => {
                if (valid) {
                    delete this.addUser.repeatPassword

                    let res = await sysAddUSer(this.addUser)
                    if (res.data.code === 200) {
                        this.$message({
                            message: '添加成功',
                            type: 'success'
                        });
                        this.addUser = {
                            orgId: '',
                            roleId: '',
                            usersName: '',
                            loginName: '',
                            password: '',
                            repeatAPassword: '',
                        }
                        // 重置字段信息
                        this.$refs["addUser"].resetFields();
                        // 获得个人的
                        await this.getAllUser()
                        this.centerDialogVisible = false
                    } else {
                        this.$message.error(res.data.msg)
                    }
                } else {
                    this.$message.error('请确保信息完整！')
                    return false;
                }
            })
        },
        handleSizeChange(val) {
            this.theData.pageSize = val
            this.searchCondition(0)

        },
        handleCurrentChange(val) {
            this.currentPage = val
            this.searchCondition(0)
        },

        // 获得用户信息
        async getAllUser() {
            this.loading = true
            let data = this.currentPage + '/' + this.theData.pageSize
            let res = await getAllUser(data)
            if (res) {
                this.loading = false
            }
            if (res.data.code === 200) {
                this.userTable = res.data.data.record
                this.total = res.data.data.total
            } else {
                this.$message({
                    message: `${res.data.data.msg}`,
                    type: 'warning'
                });
            }
        },
        // 重置别人的密码
        submitReset() {
            this.$refs.form.validate(async (valid) => {
                if (valid) {
                    delete this.resetPassword.repeatAPassword
                    let theData = {
                        loginName: this.loginName,
                        newPwd: this.resetPassword.password,
                    }
                    let res = await reqResetPassword(theData)
                    if (res.data.code == 200) {
                        this.$message({
                            type: 'success',
                            message: '重置成功！！！'
                        })
                        this.$refs["form"].resetFields();
                        this.showReset = false
                    } else {
                        this.$message.error(res.data.msg)
                    }
                }
            })

        },
        // 取消重置
        cancelReset() {
            this.showReset = false
            Object.keys(this.resetPassword).forEach(index => this.resetPassword[index] = '')
            this.$message({
                message: '已取消操作',
            });
        },
        // 取消用户添加操作
        cancelAddUser() {
            this.$refs["addUser"].resetFields();
            this.centerDialogVisible = false
            this.addUser = {
                roles: '',
                userName: '',
                loginName: '',
                password: '',
                repeatAPassword: '',
                unitName: ''
            }
            this.$message({
                message: '已取消操作',
            });

        },
        // 删除用户
        delUser(row) {
            if (row.userId === this.userId) {
                this.$message('当前账号！不能重置密码');
            } else {
                this.$confirm('确认删除该用户吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {

                    let res = await deleteUser(row.userId)
                    if (res.data.code === 200) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        await this.getGetUser()
                    } else {
                        this.$message.error(res.data.msg)
                    }

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }

        },
        confirmPassword(row) {
            // console.log(row)
            if (row.userId === this.userId) {
                this.$message.error("当前账号！不能重置密码")
            }else {
                this.resetPassword.password = ''
                this.resetPassword.repeatAPassword = ''
                this.loginName = row.loginName
                this.showReset = true
            }
        },
        open() {
            this.$confirm('此操作将永久删除选中的单位信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },


    }
}
</script>

<style scoped>

</style>
<style>
.el-tag + .el-tag {
    margin-left: 10px;
}

.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}

.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>
